package com.mxpio.erp.workshop.controller;

import java.io.UnsupportedEncodingException;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.mxpio.erp.common.enums.OrderStatusEnums;
import com.mxpio.erp.common.jpa.model.Order;
import com.mxpio.erp.common.service.OrderService;
import com.mxpio.erp.common.workshop.entity.ManufactureOrder;
import com.mxpio.erp.common.workshop.entity.ManufactureOrderItem;
import com.mxpio.erp.common.workshop.service.ManufactureOrderItemService;
import com.mxpio.erp.common.workshop.service.ManufactureOrderService;
import com.mxpioframework.common.vo.Result;
import com.mxpioframework.jpa.policy.CrudContext;
import com.mxpioframework.jpa.policy.impl.SmartCrudPolicyAdapter;
import com.mxpioframework.jpa.query.Criteria;
import com.mxpioframework.jpa.query.CriteriaUtils;
import com.mxpioframework.jpa.query.Operator;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

@Api(value = "ManufactureOrderController", tags = { "生产订单接口" })
@RestController
@RequestMapping("/erp/workshop/mo/")
public class ManufactureOrderController {

	@Autowired
	private ManufactureOrderService manufactureOrderService;
	
	@Autowired
	private ManufactureOrderItemService manufactureOrderItemService;
	
	@Autowired
	private OrderService bizOrderService;
	
	@GetMapping("list")
    @ApiOperation(value = "生产订单列表", notes = "获取生产订单列表（无分页）", httpMethod = "GET")
    public Result<List<ManufactureOrder>> list(@ApiParam(name="查询参数")  String criteria) throws UnsupportedEncodingException {
        Criteria c = CriteriaUtils.json2Criteria(criteria);
        List<ManufactureOrder> manufactureOrders = manufactureOrderService.list(ManufactureOrder.class, c);
        return Result.OK(manufactureOrders);
    }

    @GetMapping("page")
    @ApiOperation(value = "生产订单列表", notes = "获取生产订单列表（分页）", httpMethod = "GET")
    public Result<Page<ManufactureOrder>> page(@ApiParam(name="查询参数")String criteria, @ApiParam(name="每页条数")Integer pageSize, @ApiParam(name="页号")Integer pageNo) throws UnsupportedEncodingException {
        Pageable page = PageRequest.of(pageNo-1, pageSize);
        Criteria c = CriteriaUtils.json2Criteria(criteria);
        Page<ManufactureOrder> manufactureOrders = manufactureOrderService.listPage(ManufactureOrder.class, page, c);
        return Result.OK(manufactureOrders);
    }

    @GetMapping("list/{bizNo}")
    @ApiOperation(value = "根据bizNo获取生产订单", notes = "根据bizNo获取生产订单", httpMethod = "GET")
    public Result<ManufactureOrder> getById(@ApiParam(name="业务单号") @PathVariable(name = "bizNo", required = true) String bizNo) {
        ManufactureOrder manufactureOrder = manufactureOrderService.getById(ManufactureOrder.class, bizNo);
        return Result.OK(manufactureOrder);
    }

    @RequestMapping("save")
    @ApiOperation(value = "保存生产订单", notes = "保存生产订单")
    public Result<ManufactureOrder> save(@RequestBody ManufactureOrder manufactureOrder) {
        manufactureOrderService.save(manufactureOrder,new SmartCrudPolicyAdapter(){
        	@Override
        	public boolean beforeInsert(CrudContext context) {
        		Object o = context.getEntity();
        		if(o instanceof ManufactureOrderItem){
        			ManufactureOrder manufactureOrder = context.getParent();
                    ((ManufactureOrderItem) o).setBizNo(manufactureOrder.getBizNo());
        		}
        		return true;
        	}
        });
        return Result.OK(manufactureOrder);
    }

    @DeleteMapping("remove/{bizNos}")
    @ApiOperation(value = "根据bizNo删除生产订单", notes = "删除生产订单", httpMethod = "DELETE")
    @Transactional(readOnly = false)
    public Result<ManufactureOrder> remove(@ApiParam(name="业务单号，多个单号用英文逗号分隔") @PathVariable(name = "bizNos", required = true) String bizNos) {
        String[] bizNo = bizNos.split(",");
        for(String key : bizNo){
        	Criteria c = Criteria.create().addCriterion("bizNo", Operator.EQ, key);
        	manufactureOrderItemService.removeBatch(ManufactureOrderItem.class, c);
            manufactureOrderService.delete(ManufactureOrder.class, key);
        }
        return Result.OK();
    }
    
    @PutMapping("submit/{bizNo}")
    @ApiOperation(value = "提交生产订单", notes = "提交生产订单", httpMethod = "PUT")
    public Result<? extends Order> submit(@ApiParam(name="业务单号") @PathVariable(name = "bizNo", required = true) String bizNo) {
    	ManufactureOrder so = manufactureOrderService.getById(ManufactureOrder.class,bizNo);
    	if(so.getBpmnStatus().equals(OrderStatusEnums.BpmnStatus.CREATE.getStatusCode())){
    		return bizOrderService.updateBpmnStatus(so, OrderStatusEnums.BpmnStatus.AUDITING);
    	}else {
    		return Result.error("非开立状态不可提交");
		}
    }

    @PutMapping("audit/{bizNo}")
    @ApiOperation(value = "审核生产订单", notes = "审核生产订单", httpMethod = "PUT")
    public Result<? extends Order> audit(@ApiParam(name="业务单号") @PathVariable(name = "bizNo", required = true) String bizNo) {
    	ManufactureOrder so = manufactureOrderService.getById(ManufactureOrder.class,bizNo);
    	if(so.getBpmnStatus().equals(OrderStatusEnums.BpmnStatus.AUDITING.getStatusCode())){
    		return bizOrderService.updateBpmnStatus(so, OrderStatusEnums.BpmnStatus.AUDITED);
    	}else {
    		return Result.error("非审核中状态不可审核");
		}
    }

    @PutMapping("abandon/{bizNo}")
    @ApiOperation(value = "弃审生产订单", notes = "弃审生产订单", httpMethod = "PUT")
    public Result<? extends Order> abandon(@ApiParam(name="业务单号") @PathVariable(name = "bizNo", required = true) String bizNo) {
    	ManufactureOrder mo = manufactureOrderService.getById(ManufactureOrder.class,bizNo);
    	if(mo.getBpmnStatus().equals(OrderStatusEnums.BpmnStatus.AUDITING.getStatusCode())||mo.getBpmnStatus().equals(OrderStatusEnums.BpmnStatus.AUDITED.getStatusCode())){
    		return bizOrderService.updateBpmnStatus(mo, OrderStatusEnums.BpmnStatus.CREATE);
    	}else{
    		return Result.error("非审核中、已审核状态不可审核");
    	}
    }

    @PutMapping("export/{bizNos}")
    @ApiOperation(value = "导出生产订单", notes = "导出生产订单", httpMethod = "PUT")
    public Result<ManufactureOrder> export(@ApiParam(name="业务单号，多个单号用英文逗号分隔") @PathVariable(name = "bizNos", required = true) String bizNos) {
        //TODO:导出逻辑
        return Result.OK();
    }

    @PutMapping("open/{bizNo}")
    @ApiOperation(value = "打开生产订单", notes = "打开生产订单", httpMethod = "PUT")
    public Result<? extends Order> open(@ApiParam(name="业务单号") @PathVariable(name = "bizNo", required = true) String bizNo) {
    	ManufactureOrder mo = manufactureOrderService.getById(ManufactureOrder.class,bizNo);
    	return bizOrderService.updateCloseStatus(mo, OrderStatusEnums.CloseStatus.OPEN);
    }

    @PutMapping("close/{bizNo}")
    @ApiOperation(value = "关闭生产订单", notes = "关闭生产订单", httpMethod = "PUT")
    public Result<? extends Order> close(@ApiParam(name="业务单号") @PathVariable(name = "bizNo", required = true) String bizNo) {
    	ManufactureOrder mo = manufactureOrderService.getById(ManufactureOrder.class,bizNo);
    	return bizOrderService.updateCloseStatus(mo, OrderStatusEnums.CloseStatus.CLOSED);
    }
}
